package edu.hnui.shop.aspect;


import edu.hnui.shop.anotations.AdminPermission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Aspect
@Configuration  //当前类被Spring容器作为bean进行管理
public class ControllerAspect {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;
    /**
     * 管理员访问之前进行权限校验
     * @return
     */
    @Around("execution(* edu.hnui.shop.controller.admin.*.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object adminAccessBeforeValidation(ProceedingJoinPoint joinPoint) throws Throwable{
        //目标方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        AdminPermission adminPermission = method.getAnnotation(AdminPermission.class);
        if(adminPermission ==null){ //为公共方法，无需进行管理员权限的校验
            //执行目标方法，并且返回结果
            Object result = joinPoint.proceed();
            return result;
        }
        // 需要进行管理员权限的校验
        String adminName =(String)request.getSession().getAttribute("ADMIN_NAME");
        if(adminName==null){
             //重定向到login.html页面
            response.sendRedirect("/admin/admin/loginPage");
            return null;
        }else{
            Object result = joinPoint.proceed();
            return result;
        }
    }

}
